package net;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpSer {
    private ServerSocket serverSocket = null;
    public TcpSer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        ExecutorService service = Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket = serverSocket.accept();
//            Thread t = new Thread(()->{
//                processConnection(clientSocket);
//
//            });
//            t.start();
            service.submit(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("客户端上线![%s,%d]\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(System.in);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while(true){
                if(!scanner.hasNext()){
                    break;
                }
            }
            String request = scanner.next();

            String response = process(request);
            printWriter.println(response);
            printWriter.flush();
            System.out.printf("客户端下线![%s,%d]\n",clientSocket.getInetAddress(),clientSocket.getPort());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.printf("客户端下线![%s,%d]\n",clientSocket.getInetAddress(),clientSocket.getPort());
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }
}
